package com.cgx.service.impl;

import com.cgx.dao.FriendRelationDao;
import com.cgx.dao.UserDao;
import com.cgx.dao.UserInfoDao;
import com.cgx.entity.User.FriendRelation;
import com.cgx.entity.User.User;
import com.cgx.entity.User.UserInfo;
import com.cgx.entity.message.Message;
import com.cgx.entity.message.Session;
import com.cgx.entity.message.SessionUser;
import com.cgx.service.FriendService;
import com.cgx.service.MessageService;
import com.cgx.utils.UUIDUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenguanxin
 * @date 2021-05-26 22:53
 */

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private FriendRelationDao friendRelationDao;

    @Autowired
    private MessageService messageService;

    @Override
    public Object addFriend(Map<String, Object> data) {
        Assert.notNull(data, "请求不能为空");
        Assert.hasText((String) data.get("fromUserId"), "fromUserId不能为空");
        String fromUserId = String.valueOf(data.get("fromUserId"));
        Assert.hasText((String) data.get("toUserId"), "toUserId不能为空");
        String toUserId = String.valueOf(data.get("toUserId"));
        Assert.isTrue(!fromUserId.equals(toUserId), "不可以添加自己为好友");
        List<FriendRelation> friendRelationList = friendRelationDao.findAllByMainUserIdAndFriendUserIdAndIsDelete(fromUserId, toUserId, 0);
        List<FriendRelation> friendRelationListTemp = friendRelationDao.findAllByMainUserIdAndFriendUserIdAndIsDelete(toUserId, fromUserId, 0);
        if (CollectionUtils.isEmpty(friendRelationList)) {
            friendRelationList = new ArrayList<>();
        }
        if (CollectionUtils.isNotEmpty(friendRelationListTemp)) {
            friendRelationList.addAll(friendRelationListTemp);
        }
        if (CollectionUtils.isNotEmpty(friendRelationList)) {
            FriendRelation friendRelation = friendRelationList.get(0);
            Assert.isTrue(0 == friendRelation.getIsAgree(), "你们已是好友");
            if (friendRelation.getFriendUserId().equals(fromUserId)) {
                Session session = Session.getSession(fromUserId);
                String sessionId = UUIDUtils.getUUID();
                session.setSessionId(sessionId);
                session.setSessionType("1");
                messageService.saveAllSession(new ArrayList<>(Collections.singleton(session)));
                friendRelation.setSessionId(sessionId);
                friendRelation.setIsAgree(1);
                friendRelationDao.save(friendRelation);
                SessionUser fromSessionUser = SessionUser.getSessionUser(sessionId, fromUserId);
                SessionUser toSessionUser = SessionUser.getSessionUser(sessionId, toUserId);
                List<SessionUser> sessionUserList = new ArrayList<>(Arrays.asList(fromSessionUser, toSessionUser));
                messageService.saveAllSessionUser(sessionUserList);
                Message message = Message.getMessage("system");
                String messageId = UUIDUtils.getUUID();
                message.setMessageId(messageId);
                message.setSessionId(sessionId);
                message.setType(0);
                message.setContent("你们已成为好友, 来聊聊天吧");
                messageService.saveAllMessage(new ArrayList<>(Collections.singletonList(message)));
            }
        } else {
            FriendRelation friendRelation = new FriendRelation();
            friendRelation.setRelationId(UUIDUtils.getUUID());
            friendRelation.setMainUserId(fromUserId);
            friendRelation.setFriendUserId(toUserId);
            friendRelation.setIsAgree(0);
            friendRelation.setCreateBy(fromUserId);
            friendRelation.setCreateTime(new Date());
            friendRelation.setUpdateBy(toUserId);
            friendRelation.setUpdateTime(new Date());
            friendRelation.setIsDelete(0);
            friendRelationDao.save(friendRelation);
        }
        return null;
    }

    @Override
    public List<FriendRelation> queryFriend(List<String> relationIdList) {
        Assert.notEmpty(relationIdList, "relationIdList不能为空");
        List<FriendRelation> friendRelationList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(relationIdList)) {
            friendRelationList = friendRelationDao.findAllByRelationIdInAndIsDelete(relationIdList, 0);
        }
        return friendRelationList;
    }

    @Override
    public List<FriendRelation> queryFriendBySessionId(List<String> idList) {
        List<FriendRelation> friendRelationList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(idList)) {
            friendRelationList = friendRelationDao.findAllBySessionIdInAndIsDelete(idList, 0);
        }
        return friendRelationList;
    }

    @Override
    public List<Map<String, Object>> queryBySearchText(Map<String, Object> data) {
        Assert.notNull(data, "请求不能为空");
        Assert.notNull(data.get("searchText"), "searchText不能为空");
        String searchText = data.get("searchText").toString();
        List<Map<String, Object>> result = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<User> loginNameList = userDao.findAllByLoginNameAndIsDelete(searchText, 0);
        if (CollectionUtils.isNotEmpty(loginNameList)) {
            userList.addAll(loginNameList);
        }
        List<User> phoneList = userDao.findAllByPhoneAndIsDelete(searchText, 0);
        if (CollectionUtils.isNotEmpty(phoneList)) {
            userList.addAll(phoneList);
        }
        Set<String> userIdSet = userList.stream().map(User :: getUserId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(userIdSet)) {
            List<UserInfo> userInfoList = userInfoDao.findAllByUserIdInAndIsDelete(new ArrayList<>(userIdSet), 0);
            if (CollectionUtils.isNotEmpty(userInfoList)) {
                result = userInfoList.stream().map(userInfo -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userInfo.getUserId());
                    map.put("userName", userInfo.getUserName());
                    map.put("avatarUrl", userInfo.getAvatarUrl());
                    return map;
                }).collect(Collectors.toList());
            }
        }
        return result;
    }


}
